3 use Wikimedia\Rdbms\Blob
;
4 use Wikimedia\Rdbms\Database
;
5 use Wikimedia\Rdbms\DatabaseSqlite
;
6 use Wikimedia\Rdbms\ResultWrapper
;
13 class DatabaseSqliteTest
extends MediaWikiTestCase
{
14 /** @var DatabaseSqliteMock */
17 protected function setUp() {
20 if ( !Sqlite
::isPresent() ) {
21 $this->markTestSkipped( 'No SQLite support detected' );
23 $this->db
= DatabaseSqliteMock
::newInstance();
24 if ( version_compare( $this->db
->getServerVersion(), '3.6.0', '<' ) ) {
25 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
29 private function replaceVars( $sql ) {
30 // normalize spacing to hide implementation details
31 return preg_replace( '/\s+/', ' ', $this->db
->replaceVars( $sql ) );
34 private function assertResultIs( $expected, $res ) {
35 $this->assertNotNull( $res );
37 foreach ( $res as $row ) {
38 foreach ( $expected[$i] as $key => $value ) {
39 $this->assertTrue( isset( $row->$key ) );
40 $this->assertEquals( $value, $row->$key );
44 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
47 public static function provideAddQuotes() {
53 'foo bar', "'foo bar'"
55 [ // #2: including quote
56 'foo\'bar', "'foo''bar'"
58 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
63 [ // #4: blob object (must be represented as hex)
75 * @dataProvider provideAddQuotes()
76 * @covers DatabaseSqlite::addQuotes
78 public function testAddQuotes( $value, $expected ) {
80 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
81 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
83 // ok, quoting works as expected, now try a round trip.
84 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
86 $this->assertTrue( $re !== false, 'query failed' );
88 $row = $re->fetchRow();
90 if ( $value instanceof Blob
) {
91 $value = $value->fetch();
94 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
96 $this->fail( 'query returned no result' );
101 * @covers DatabaseSqlite::replaceVars
103 public function testReplaceVars() {
104 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
107 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
108 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
110 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
111 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
112 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
117 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
119 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
123 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
124 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
127 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
128 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
132 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
133 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
135 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
136 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
139 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
140 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
143 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
144 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
147 $this->assertEquals( "DROP INDEX foo",
148 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
151 $this->assertEquals( "DROP INDEX foo -- dropping index",
152 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
154 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
155 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
160 * @covers DatabaseSqlite::tableName
162 public function testTableName() {
164 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
165 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
166 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
167 $db->tablePrefix( 'foo' );
168 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
169 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
173 * @covers DatabaseSqlite::duplicateTableStructure
175 public function testDuplicateTableStructure() {
176 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
177 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
178 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
179 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
181 $db->duplicateTableStructure( 'foo', 'bar' );
182 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
183 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
184 'Normal table duplication'
186 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
187 $index = $indexList->next();
188 $this->assertEquals( 'bar_index1', $index->name
);
189 $this->assertEquals( '0', $index->unique
);
190 $index = $indexList->next();
191 $this->assertEquals( 'bar_index2', $index->name
);
192 $this->assertEquals( '1', $index->unique
);
194 $db->duplicateTableStructure( 'foo', 'baz', true );
195 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
196 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
197 'Creation of temporary duplicate'
199 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
200 $index = $indexList->next();
201 $this->assertEquals( 'baz_index1', $index->name
);
202 $this->assertEquals( '0', $index->unique
);
203 $index = $indexList->next();
204 $this->assertEquals( 'baz_index2', $index->name
);
205 $this->assertEquals( '1', $index->unique
);
206 $this->assertEquals( 0,
207 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
208 'Create a temporary duplicate only'
213 * @covers DatabaseSqlite::duplicateTableStructure
215 public function testDuplicateTableStructureVirtual() {
216 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
217 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
218 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
220 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
222 $db->duplicateTableStructure( 'foo', 'bar' );
223 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
224 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
225 'Duplication of virtual tables'
228 $db->duplicateTableStructure( 'foo', 'baz', true );
229 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
230 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
231 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
236 * @covers DatabaseSqlite::deleteJoin
238 public function testDeleteJoin() {
239 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
240 $db->query( 'CREATE TABLE a (a_1)', __METHOD__
);
241 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__
);
250 [ 'b_1' => 2, 'b_2' => 'a' ],
251 [ 'b_1' => 3, 'b_2' => 'b' ],
255 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__
);
256 $res = $db->query( "SELECT * FROM a", __METHOD__
);
257 $this->assertResultIs( [
268 public function testEntireSchema() {
271 $result = Sqlite
::checkSqlSyntax( "$IP/maintenance/tables.sql" );
272 if ( $result !== true ) {
273 $this->fail( $result );
275 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
279 * Runs upgrades of older databases and compares results with current schema
280 * @todo Currently only checks list of tables
283 public function testUpgrades() {
284 global $IP, $wgVersion, $wgProfiler;
288 // '1.13', disabled for now, was totally screwed up
289 // SQLite wasn't included in 1.14
301 // Mismatches for these columns we can safely ignore
303 'user_newtalk.user_last_timestamp', // r84185
306 $currentDB = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
307 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
309 $profileToDb = false;
310 if ( isset( $wgProfiler['output'] ) ) {
311 $out = $wgProfiler['output'];
312 if ( $out === 'db' ) {
314 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
319 if ( $profileToDb ) {
320 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
322 $currentTables = $this->getTables( $currentDB );
323 sort( $currentTables );
325 foreach ( $versions as $version ) {
326 $versions = "upgrading from $version to $wgVersion";
327 $db = $this->prepareTestDB( $version );
328 $tables = $this->getTables( $db );
329 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
330 foreach ( $tables as $table ) {
331 $currentCols = $this->getColumns( $currentDB, $table );
332 $cols = $this->getColumns( $db, $table );
334 array_keys( $currentCols ),
336 "Mismatching columns for table \"$table\" $versions"
338 foreach ( $currentCols as $name => $column ) {
339 $fullName = "$table.$name";
342 (bool)$cols[$name]->pk
,
343 "PRIMARY KEY status does not match for column $fullName $versions"
345 if ( !in_array( $fullName, $ignoredColumns ) ) {
347 (bool)$column->notnull
,
348 (bool)$cols[$name]->notnull
,
349 "NOT NULL status does not match for column $fullName $versions"
353 $cols[$name]->dflt_value
,
354 "Default values does not match for column $fullName $versions"
358 $currentIndexes = $this->getIndexes( $currentDB, $table );
359 $indexes = $this->getIndexes( $db, $table );
361 array_keys( $currentIndexes ),
362 array_keys( $indexes ),
363 "mismatching indexes for table \"$table\" $versions"
371 * @covers DatabaseSqlite::insertId
373 public function testInsertIdType() {
374 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
376 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
377 $this->assertInstanceOf( ResultWrapper
::class, $databaseCreation, "Database creation" );
379 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
380 $this->assertTrue( $insertion, "Insertion worked" );
382 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
383 $this->assertTrue( $db->close(), "closing database" );
387 * @covers DatabaseSqlite::insert
389 public function testInsertAffectedRows() {
390 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
391 $db->query( 'CREATE TABLE testInsertAffectedRows ( foo )', __METHOD__
);
393 $insertion = $db->insert(
394 'testInsertAffectedRows',
402 $this->assertTrue( $insertion, "Insertion worked" );
404 $this->assertSame( 3, $db->affectedRows() );
405 $this->assertTrue( $db->close(), "closing database" );
408 private function prepareTestDB( $version ) {
409 static $maint = null;
410 if ( $maint === null ) {
411 $maint = new FakeMaintenance();
412 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
416 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
417 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
418 $updater = DatabaseUpdater
::newForDB( $db, false, $maint );
419 $updater->doUpdates( [ 'core' ] );
424 private function getTables( $db ) {
425 $list = array_flip( $db->listTables() );
427 'external_user', // removed from core in 1.22
428 'math', // moved out of core in 1.18
429 'trackbacks', // removed from core in 1.19
431 'searchindex_content',
432 'searchindex_segments',
433 'searchindex_segdir',
435 'searchindex_docsize',
438 foreach ( $excluded as $t ) {
441 $list = array_flip( $list );
447 private function getColumns( $db, $table ) {
449 $res = $db->query( "PRAGMA table_info($table)" );
450 $this->assertNotNull( $res );
451 foreach ( $res as $col ) {
452 $cols[$col->name
] = $col;
459 private function getIndexes( $db, $table ) {
461 $res = $db->query( "PRAGMA index_list($table)" );
462 $this->assertNotNull( $res );
463 foreach ( $res as $index ) {
464 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
465 $this->assertNotNull( $res2 );
466 $index->columns
= [];
467 foreach ( $res2 as $col ) {
468 $index->columns
[] = $col;
470 $indexes[$index->name
] = $index;
480 public function testCaseInsensitiveLike() {
481 // TODO: Test this for all databases
482 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
483 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
484 $row = $res->fetchRow();
485 $this->assertFalse( (bool)$row['a'] );
489 * @covers DatabaseSqlite::numFields
491 public function testNumFields() {
492 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
494 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
495 $this->assertInstanceOf( ResultWrapper
::class, $databaseCreation, "Failed to create table a" );
496 $res = $db->select( 'a', '*' );
497 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
498 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
499 $this->assertTrue( $insertion, "Insertion failed" );
500 $res = $db->select( 'a', '*' );
501 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
503 $this->assertTrue( $db->close(), "closing database" );
507 * @covers \Wikimedia\Rdbms\DatabaseSqlite::__toString
509 public function testToString() {
510 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
512 $toString = (string)$db;
514 $this->assertContains( 'SQLite ', $toString );
518 * @covers \Wikimedia\Rdbms\DatabaseSqlite::getAttributes()
520 public function testsAttributes() {
521 $attributes = Database
::attributesFromType( 'sqlite' );
522 $this->assertTrue( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] );
526 class DatabaseSqliteMock
extends DatabaseSqlite
{
527 public static function newInstance( array $p = [] ) {
528 $p['dbFilePath'] = ':memory:';
529 $p['schema'] = false;
531 return Database
::factory( 'SqliteMock', $p );
534 function query( $sql, $fname = '', $tempIgnore = false ) {
539 * Override parent visibility to public
541 public function replaceVars( $s ) {
542 return parent
::replaceVars( $s );